package com.banciyuan.bcywebview.utils.update;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.app.BaseApplication;
import com.banciyuan.bcywebview.base.view.toast.MyToast;

/**
 * @author hfxt2008
 *         新版本下载完成的广播接收者，监听并打开下载完成的apk文件
 */
public class DownloadReceiver extends BroadcastReceiver {

    public DownloadReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                DownloadManager dManager = (DownloadManager) context.getSystemService(BaseApplication.DOWNLOAD_SERVICE);
                long myDwonloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                Uri downloadFileUri = findUriById(dManager, myDwonloadID, context);
                if (downloadFileUri != null) {
                    Intent mIntent = new Intent();
                    mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mIntent.setAction(Intent.ACTION_VIEW);
                    mIntent.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
                    context.getApplicationContext().startActivity(mIntent);
                } else {
                    try {
                        MyToast.show(context, context.getString(R.string.package_not_exist));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Uri findUriById(DownloadManager dm, long id, Context context) {
        Cursor q = dm.query(new DownloadManager.Query().setFilterById(id));
        if (q == null) {
            MyToast.show(context, context.getString(R.string.package_not_exist));
        }
        q.moveToFirst();
        String path = "file://" + q.getString(q.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
        Uri uri = Uri.parse(path);
        q.close();
        return uri;
    }
}
